angular.module('sort-manage', ['ngStorage'])

.controller 'sortManageCtrl', ($scope, $http, SortModal, $state, showToast, $stateParams, $ionicHistory, $ionicScrollDelegate, userData, $localStorage, dropdownMenu, $ionicPopup) ->
    $scope.$storage = $localStorage
    getSort = ->
        $http.get '/updshop/', params: {action: 'productsort', userid: userData.getToken()}
        .success (resp) ->
            if resp.status == '0'
                $scope.$storage.Allsort = resp.body
                _.each $scope.$storage.Allsort, (first) ->
                    first.show = false
                    if first.childsort != ''
                        _.each first.childsort, (second) ->
                            second.show = false
                console.log $scope.$storage.Allsort
        .error (e)->
            showToast '网络异常,请检查网络是否连接'

    $scope.goBack = ()->
        $ionicHistory.goBack()

    _.extend $scope,
        haveSort:
            selectedSort: undefined
        postSortData:
            action: 'editshopprosort'
            userid: userData.getToken()
            sortid: 0
            sortname: undefined
            sortorder: undefined
            parentid: undefined
        showSecondChild: (item) ->
            if item.childsort == '' or item.childsort.length==0
                return false
            else
                item.show = !item.show
        showThirdChild: (item) ->
            if item.childsort == '' or item.childsort.length==0
                return false
            else
                item.show = !item.show
        showSortsModal: ->
            if $scope.$storage.Allsort?.length==0
                showToast '暂无分类,请先添加'
            else
                SortModal.showModal()

        goDeleteChecksort: ->
            SortModal.clearChecksort()
        goaddSort: ->
            if  $localStorage.checkSort != undefined
                i = $localStorage.checkSort.i
                j = $localStorage.checkSort.j
                console.log i,j
                $scope.postSortData.parentid = $localStorage.checkSort.id
                $http.post('/utf-8data/', $scope.postSortData)
                .success (resp) ->
                    if resp.status == '0'
                        item = resp.body
                        if $localStorage.checkSort.j == undefined
                            item.secondsortid = item.sortid
                            $scope.$storage.Allsort[i].show = true
                            item.secondsortname = item.sortname
                            item.show = false
                            item.childsort = []
                            tmp = $scope.$storage.Allsort[i].childsort
                            tmp.push item
                            tmp = _.sortBy tmp,(obj)->
                                parseFloat(obj.sortorder)
                            $scope.$storage.Allsort[i].childsort = tmp
                        else
                            item.thirdsortid = item.sortid
                            $scope.$storage.Allsort[i].show = true
                            $scope.$storage.Allsort[i].childsort[j].show = true
                            item.thirdsortname = item.sortname
                            item.show = false
                            tmp = $scope.$storage.Allsort[i].childsort[j].childsort
                            console.log 111111,tmp
                            tmp.push item
                            tmp = _.sortBy tmp,(obj)->
                                parseFloat(obj.sortorder)
                            $scope.$storage.Allsort[i].childsort[j].childsort = tmp
                        console.log $scope.$storage.Allsort
                        showToast resp.msg
                    else
                        showToast resp.msg
                .error ->
                    showToast resp.msg
            else
                $scope.postSortData.parentid = 0
                $http.post('/utf-8data/',$scope.postSortData)
                .success (resp) ->
                    if resp.status == '0'
                        item = resp.body
                        item.firstsortid = item.sortid
                        item.show = false
                        item.childsort = []
                        item.firstsortname = item.sortname
                        $scope.$storage.Allsort.push item
                        $scope.$storage.Allsort =_.sortBy $scope.$storage.Allsort,(item)->
                            parseFloat(item.sortorder)
                        console.log $scope.$storage.Allsort
                        showToast resp.msg
                    else
                        showToast resp.msg
                .error ->
                    showToast resp.msg
        goEditSortFirst: (first)->
            console.log first
            $scope.newSort = {}
            areaPopup = $ionicPopup.show {
                template: '<input type="text" style="white-space: nowrap;" ng-model="newSort.sortname"  maxlength="8">', title: '请输入新名称'
                scope: $scope
                buttons: [
                    {
                        text: '取消'
                        onTap: () ->
                            return false
                    }
                    {
                        text: '<b>保存</b>'
                        type: 'button-positive'
                        onTap: (e) ->
                            if !$scope.newSort.sortname
                                e.preventDefault()
                            else
                                return $scope.newSort.sortname
                    }
                ]
            }
            areaPopup.then (res) ->
                if res == false
                    return
                else
                    $http.post('/utf-8data/', {
                        action: 'editshopprosort',
                        userid: userData.getToken(),
                        sortid: first.firstsortid,
                        sortname: $scope.newSort.sortname,
                        sortorder: first.sortorder,
                        parentid: 0
                    })
                    .success (resp) ->
                        if resp.status == '0'
                            showToast resp.msg
                            first.firstsortname = res
                        else
                            showToast resp.msg
                    .error ->
                        showToast resp.msg
        goEditSortSecond: (second, first)->
            console.log second, first
            $scope.newSort = {}
            areaPopup = $ionicPopup.show {
                template: '<input type="text" ng-model="newSort.sortname"  maxlength="8">', title: '请输入新名称'
                scope: $scope
                buttons: [
                    {
                        text: '取消'
                        onTap: () ->
                            return false
                    }
                    {
                        text: '<b>保存</b>'
                        type: 'button-positive'
                        onTap: (e) ->
                            if !$scope.newSort.sortname
                                e.preventDefault()
                            else
                                return $scope.newSort.sortname
                    }
                ]
            }
            areaPopup.then (res) ->
                if res == false
                    return
                else
                    $http.post('/utf-8data/', {
                        action: 'editshopprosort',
                        userid: userData.getToken(),
                        sortid: second.secondsortid,
                        sortname: $scope.newSort.sortname,
                        sortorder: second.sortorder,
                        parentid: first.firstsortid
                    })
                    .success (resp) ->
                        if resp.status == '0'
                            showToast resp.msg
                            second.secondsortname = res
                        else
                            showToast resp.msg
                    .error ->
                        showToast resp.msg
        goEditSortThird: (third, second) ->
            console.log second, third
            $scope.newSort = {}
            areaPopup = $ionicPopup.show {
                template: '<input type="text" ng-model="newSort.sortname"  maxlength="8">', title: '请输入新名称'
                scope: $scope
                buttons: [
                    {
                        text: '取消'
                        onTap: () ->
                            return false
                    }
                    {
                        text: '<b>保存</b>'
                        type: 'button-positive'
                        onTap: (e) ->
                            if !$scope.newSort.sortname
                                e.preventDefault()
                            else
                                return $scope.newSort.sortname
                    }
                ]
            }
            areaPopup.then (res) ->
                if res == false
                    return
                else
                    $http.post('/utf-8data/', {
                        action: 'editshopprosort',
                        userid: userData.getToken(),
                        sortid: third.thirdsortid,
                        sortname: $scope.newSort.sortname,
                        sortorder: third.sortorder,
                        parentid: second.secondsortid
                    })
                    .success (resp) ->
                        if resp.status == '0'
                            showToast resp.msg
                            third.thirdsortname = res
                        else
                            showToast resp.msg
                    .error (err)->
                        showToast err

        goDeleteSortFirst: (first, i) ->
            $ionicPopup.confirm({
                title:'确认删除该分类吗?'
                okText:'确认'
                cancelText:'取消'
            }).then (res) ->
                if res
                    $http.get('/updshop/',
                        params: {action: 'delprosort', userid: userData.getToken(), sortid: first.firstsortid})
                    .success (resp) ->
                        if resp.status == '0'
                            showToast '删除成功'
                            SortModal.clearChecksort()
                            $scope.$storage.Allsort.splice(i, 1)
                        else
                            showToast resp.msg
                    .error (err)->
                        showToast err
        goDeleteSortSecond: (second, i, j) ->
            $ionicPopup.confirm({
                title:'确认删除该分类吗?'
                okText:'确认'
                cancelText:'取消'
            }).then (res) ->
                if res
                    $http.get('/updshop/',
                        params: {action: 'delprosort', userid: userData.getToken(), sortid: second.secondsortid})
                    .success (resp) ->
                        if resp.status == '0'
                            showToast '删除成功'
                            SortModal.clearChecksort()
                            $scope.$storage.Allsort[i].childsort.splice(j, 1)
                            if $scope.$storage.Allsort[i].childsort.length == 0
                                $scope.$storage.Allsort[i].show = false
                        else
                            showToast resp.msg
                    .error (err)->
                        showToast err
        goDeleteSortThird: (third, i, j, k) ->
            $ionicPopup.confirm({
                title:'确认删除该分类吗?'
                okText:'确认'
                cancelText:'取消'
            }).then (res) ->
                if res
                    $http.get('/updshop/',
                        params: {action: 'delprosort', userid: userData.getToken(), sortid: third.thirdsortid})
                    .success (resp) ->
                        if resp.status == '0'
                            showToast '删除成功'
                            $scope.$storage.Allsort[i].childsort[j].childsort.splice(k, 1)
                            if $scope.$storage.Allsort[i].childsort[j].childsort.length == 0
                                $scope.$storage.Allsort[i].childsort[j].show = false
                        else
                            showToast resp.msg
                    .error (err) ->
                        showToast err
        move:(firstId,secondId,thirdId,type)->
            id=thirdId
            id=secondId if id==''
            id=firstId if id==''
            $http.get('/utf-8data/',
                params: {action: 'changesort', userid: userData.getToken(), sortid: id,stype:type})
            .success (resp) ->
                console.log resp
                if resp.status == '0'
                    showToast '移动成功'
                    doMove(firstId,secondId,thirdId,type)
                else
                    showToast resp.msg
            .error (err) ->
                showToast err.msg
    doMove=(firstId,secondId,thirdId,type)->
        #获得目标元素所在数组,及其index
        itemIndex=''
        targetList=[]
        console.log firstId,secondId,thirdId,type
        if thirdId=='' and secondId=='' #一级分类
            targetList=$scope.$storage.Allsort
            _.each targetList,(first,index)->
                if first.firstsortid==firstId
                    itemIndex=index
        else if thirdId=='' #二级分类
            firstsort=_.find $scope.$storage.Allsort,(first)->first.firstsortid==firstId if secondId!=''
            targetList=firstsort.childsort
            _.each targetList,(second,index)->
                if second.secondsortid==secondId
                    itemIndex=index
        else
            firstsort=_.find $scope.$storage.Allsort,(first)->first.firstsortid==firstId if secondId!=''
            secondsort=_.find firstsort.childsort,(second)->second.secondsortid==secondId if thirdId!=''
            targetList=secondsort.childsort
            _.each targetList,(third,index)->
                if third.thirdsortid==thirdId
                    itemIndex=index
        return if itemIndex=='' or targetList?.length<0
        #按type,对其与另一个元素进行位置交换
        if type=='up'
            return if itemIndex-1<0
            item=targetList[itemIndex]
            upItem=targetList[itemIndex-1]
            targetList.splice(Number(itemIndex-1),1,item)
            targetList.splice(Number(itemIndex),1,upItem)
        else
            return if itemIndex+1>targetList.length
            item=targetList[itemIndex]
            downItem=targetList[itemIndex+1]
            targetList.splice(Number(itemIndex),1,downItem)
            targetList.splice(Number(itemIndex+1),1,item)
    $scope.$on '$ionicView.enter', ->
        getSort()
    $scope.$on '$ionicView.beforeEnter', ->
        $localStorage.checkSort = undefined
